package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shops/models"
)

type ShopController struct {
	beego.Controller
}

func (c *ShopController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var shop models.Shop
	shop.Tel = c.GetString("tel")
	shop.Price, _ = c.GetFloat("price")
	shop.Address = c.GetString("address")
	shop.Manager = c.GetString("manager")
	shop.Status = "打烊"
	if shop.GetShopByAddress() != nil {
		c.Data["json"] = map[string]any{
			"Code": 501,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	if shop.ID != 0 {
		c.Data["json"] = map[string]any{
			"Code": 502,
			"Msg":  "当前店面已有店铺",
		}
		c.ServeJSON()
		return
	}
	if shop.CreateShop() != nil {
		c.Data["json"] = map[string]any{
			"Code": 501,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "上传成功",
	}
	c.ServeJSON()
}
func (c *ShopController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var shops []models.Shop
	if models.DB.Find(&shops).Error != nil {
		c.Data["json"] = map[string]any{
			"Code": 501,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "查询成功",
		"Data": shops,
	}
	c.ServeJSON()
	return
}
func (c *ShopController) Update() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var shop models.Shop
	shop.Address = c.GetString("old_address")
	if shop.GetShopByAddress() != nil {
		c.Data["json"] = map[string]any{
			"Code": 501,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	if c.Ctx.Input.Method() == "GET" {
		c.Data["json"] = map[string]any{
			"Code": 200,
			"Msg":  "查询成功",
			"Data": shop,
		}
		c.ServeJSON()
		return
	}
	if shop.GetShopByAddress() != nil {
		c.Data["json"] = map[string]any{
			"Code": 501,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	shop.Address = c.GetString("address")
	shop.Tel = c.GetString("tel")
	shop.Price, _ = c.GetFloat("price")
	shop.Manager = c.GetString("manager")
	if shop.UpdateShop() != nil {
		c.Data["json"] = map[string]any{
			"Code": 501,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "修改成功",
	}
	c.ServeJSON()
	return
}
